package com.infore.airsupervise.ui.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.DefaultAxisValueFormatter;
import com.github.mikephil.charting.formatter.DefaultValueFormatter;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.PointAnalyzeTableAdapter;
import com.infore.airsupervise.adapter.StationExpandAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.app.StatusConst;
import com.infore.airsupervise.bean.MenuE;
import com.infore.airsupervise.bean.PointAnalyzeE;
import com.infore.airsupervise.biz.StatisticsBiz;
import com.infore.airsupervise.biz.impl.StatisticsBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.fragment.StationTreeFragment;
import com.infore.airsupervise.ui.widget.MyMarkerView;
import com.infore.airsupervise.utils.DateUtil;
import com.infore.airsupervise.utils.ToastUtil;
import com.inqbarna.tablefixheaders.TableFixHeaders;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 点位分析
 *
 * 作者: dingxinlin
 * 创建时间: 2017/8/22 17:45
 */
public class PointAnalyzeActivity extends BaseTitleBarActivity
        implements OnChartValueSelectedListener, TimePickerView.OnTimeSelectListener, OptionsPickerView.OnOptionsSelectListener {

    @BindView(R.id.drawer_container)
    FrameLayout drawerContainer;
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.barChart)
    BarChart mChart;
    @BindView(R.id.scroll_table)
    TableFixHeaders scrollTable;
    @BindView(R.id.tv_time)
    EditText tvTime;
    @BindView(R.id.sel_factor)
    TextView selFactor;

    private TimePickerView timePickerView;
    private OptionsPickerView<String> factorPicker;

    private StationTreeFragment drawerFrag;    // 抽屉Fragment
    private StatisticsBiz statisticsBiz;    // 业务类
    private List<PointAnalyzeE> datas;

    private String curTypeStr =null;
    private int curType ;
    private String time ;
    private String curMNs = "";
    private boolean[] showType = new boolean[]{true, true, true, false, false, false};
    private List<String> factorList;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_point_analyze);
        ButterKnife.bind(this);

        statisticsBiz = new StatisticsBizImpl();

        initView();
        initChart();
    }

    private void initView() {
        mChart.setNoDataText("暂无数据，请搜索");

        // 获取携带数据
        Bundle bundle = getIntent().getExtras();
        MenuE menuE = (MenuE) bundle.getSerializable(Constants.INTENT_OBJ_KEY);

        // 初始化标题栏
        title.setText(menuE.getTitle());
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_TABLE);


        //因子
        factorList = new ArrayList<>();
        factorList = Arrays.asList(getResources().getStringArray(R.array.airType2));
        curType = StatusConst.AIR_TYPE_PM10;
        curTypeStr = factorList.get(0);
        selFactor.setText(curTypeStr);
        //时间
        time = DateUtil.updateTime(DateUtil.getCurrentDateStr(DateUtil.FORMAT_DATE),StatusConst.STATISTIC_DAY,false);
        tvTime.setText(time);

        // 提示选择站点
      //  ToastUtil.showLong(this, "请选择站点进行分析");
        getAnalyzeDatas();
    }

    /**
     * 切换图表、表格
     *
     * @param view
     */
    @Override
    protected void onRightMenuClick(View view) {
        boolean isSel = rightMenu.isSelected();
        if (isSel) {
            rightMenu.setFontAwesomeIcon(FontAwesome.FA_TABLE);
            mChart.setVisibility(View.VISIBLE);
            scrollTable.setVisibility(View.INVISIBLE);
        } else {
            rightMenu.setFontAwesomeIcon(FontAwesome.FA_BAR_CHART);
            mChart.setVisibility(View.INVISIBLE);
            scrollTable.setVisibility(View.VISIBLE);
        }
        rightMenu.setSelected(!isSel);
    }

    /**
     * 获取分析数据
     */
    private void getAnalyzeDatas() {
        final SweetAlertDialog dialog = new SweetAlertDialog(ctx, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING);
        dialog.show();
        statisticsBiz.getPointAnalyze(curType, time, curMNs,
                new OnServerResponseListener<List<PointAnalyzeE>>() {
                    @Override
                    public void onSucceed(List<PointAnalyzeE> result, String desc) {
                        // 数据少于两组时提示
//                        if (result.size() < 2) {
//                            dialog.setTitleText("部分站点数据为空")
//                                    .setContentText("请选择有数据的站点进行分析")
//                                    .changeAlertType(SweetAlertDialog.WARNING_TYPE);
//                            return;
//                        }

                        dialog.dismiss();
                        if(result == null || result.size()<= 0 ){
                            return ;
                        }
                        datas = result;
                        setChartData();
                        initTable();
                    }

                    @Override
                    public void onFailed(int errorCode, String title, String desc) {
                        dialog.setTitleText(title)
                                .setContentText(desc)
                                .setConfirmText(MsgConst.I_SEE)
                                .changeAlertType(SweetAlertDialog.WARNING_TYPE);
                    }
                });
    }

    /**
     * 初始化表格
     */
    private void initTable() {
        if (null == datas) {
            return;
        }

        String[] topTitles = new String[datas.size()];
        String[] leftTitles = new String[datas.get(0).getVlist().size()];
        String[][] contents = new String[datas.get(0).getVlist().size()][datas.size()];

        for (int i = 0; i < datas.size(); i++) {
            PointAnalyzeE sta = datas.get(i);
            topTitles[i] = sta.getName();

            List<PointAnalyzeE.VlistBean> staVlist = sta.getVlist();
            if (staVlist == null) {
                break;
            }

            for (int j = 0; j < staVlist.size(); j++) {
                PointAnalyzeE.VlistBean value = staVlist.get(j);
                leftTitles[j] = value.getTime();
                contents[j][i] = value.getValue() + "";
            }
        }

        scrollTable.setAdapter(new PointAnalyzeTableAdapter(ctx, topTitles, leftTitles, contents));

    }

    /**
     * 初始化图表
     */
    private void initChart() {
        mChart.setOnChartValueSelectedListener(this);
        mChart.setDrawBarShadow(false);
        mChart.setDrawValueAboveBar(true);
        mChart.getDescription().setEnabled(false);

        // scaling can now only be done on x- and y-axis separately
        mChart.setPinchZoom(false);
        mChart.setDrawBarShadow(false);
        mChart.setDrawGridBackground(false);

        // create a custom MarkerView (extend MarkerView) and specify the layout to use for it
        MyMarkerView mv = new MyMarkerView(this, R.layout.custom_marker_view);
        mv.setChartView(mChart); // For bounds control
        mChart.setMarker(mv); // Set the marker to the chart

        Legend l = mChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.TOP);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.RIGHT);
        l.setOrientation(Legend.LegendOrientation.VERTICAL);
        l.setDrawInside(true);
        l.setTextSize(8f);

        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setCenterAxisLabels(true);
        xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return (int) value + ":00";
            }
        });

        YAxis leftAxis = mChart.getAxisLeft();
        leftAxis.setValueFormatter(new DefaultAxisValueFormatter(0));
        leftAxis.setDrawGridLines(false);
        leftAxis.setSpaceTop(35f);
        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)
        leftAxis.setGranularityEnabled(true);

        // 隐藏右边Y轴
        mChart.getAxisRight().setEnabled(false);
    }

    /**
     * 设置图表数据
     */
    private void setChartData() {

        int gCount = datas.size();
        int xCount = 0;

        float groupSpace = 0.08f;
        float barSpace = 0.12f / gCount;
        float barWidth = 0.8f / gCount;
        // (0.2 + 0.03) * 4 + 0.08 = 1.00 -> interval per "group"

        List<List<BarEntry>> yVals = new ArrayList<>();

        for (int i = 0; i < gCount; i++) {
            List<BarEntry> yVal = new ArrayList<>();

            PointAnalyzeE sta = datas.get(i);
            List<PointAnalyzeE.VlistBean> staVlist = sta.getVlist();
            if (staVlist == null) {
                break;
            }

            xCount = staVlist.size();

            for (int j = 0; j < staVlist.size(); j++) {
                PointAnalyzeE.VlistBean value = staVlist.get(j);
                String desc = sta.getName() + "\n" + curTypeStr + "：" + value.getValue();
                yVal.add(new BarEntry(j, (float) value.getValue(), desc));
            }

            yVals.add(yVal);
        }

        IBarDataSet[] sets = new IBarDataSet[gCount];

        // 颜色集合
        ArrayList<Integer> colors = new ArrayList<>();
        for (int c : ColorTemplate.COLORFUL_COLORS)
            colors.add(c);
        for (int c : ColorTemplate.PASTEL_COLORS)
            colors.add(c);

        // 创建DataSet
        for (int i = 0; i < gCount; i++) {
            PointAnalyzeE sta = datas.get(i);
            BarDataSet set = new BarDataSet(yVals.get(i), sta.getName());
            set.setColor(colors.get(i));
            sets[i] = set;
        }

        BarData data = new BarData(sets);
        data.setValueFormatter(new DefaultValueFormatter(2));

        mChart.setData(data);

        // specify the width each bar should have
        mChart.getBarData().setBarWidth(barWidth);

        // restrict the x-axis range
        mChart.getXAxis().setAxisMinimum(0);


        if(gCount>=2){
            // barData.getGroupWith(...) is a helper that calculates the width each group needs based on the provided parameters
            mChart.getXAxis().setAxisMaximum(0 + mChart.getBarData().getGroupWidth(groupSpace, barSpace) * xCount);
            mChart.groupBars(0, groupSpace, barSpace);
            mChart.getXAxis().setCenterAxisLabels(true);
        }else {
            mChart.getXAxis().setCenterAxisLabels(false);
        }
        mChart.invalidate();
    }

    protected RectF mOnValueSelectedRectF = new RectF();

    @SuppressLint("NewApi")
    @Override
    public void onValueSelected(Entry e, Highlight h) {
        if (e == null)
            return;
        RectF bounds = mOnValueSelectedRectF;
        mChart.getBarBounds((BarEntry) e, bounds);
        MPPointF position = mChart.getPosition(e, YAxis.AxisDependency.LEFT);
        MPPointF.recycleInstance(position);
    }

    @Override
    public void onNothingSelected() {

    }


    /**
     * 初始化时间选择
     */
    private void initDatePicker(){
        Calendar endSelectedDate = Calendar.getInstance();
        endSelectedDate.add(Calendar.DAY_OF_MONTH,-1);
        timePickerView = new TimePickerView.Builder(ctx,this)
                .setTitleText("")
                .setLabel("年", "月", "日", "点", "分", "秒")
                .setType(showType)
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(18)
                .setDate(endSelectedDate)
                .setRangDate(null , Calendar.getInstance())
                .setDecorView(null)
                .build();
    }

    /**
     * 因子选择器
     */
    private void initFactorPicker(){

        factorPicker = new OptionsPickerView.Builder(ctx , this)
                .isCenterLabel(false)
                .setTitleText("因子")
                .setDividerColor(Color.DKGRAY)
                .setDecorView(null)
                .build();
        factorPicker.setPicker(factorList);
    }

    /**
     * 加减一段时间
     * @param offset
     * @return
     */
    private boolean timeOffset(int offset){
        boolean isEnd = DateUtil.compareDate(time,DateUtil.getCurrentDateStr(DateUtil.FORMAT_DATE),DateUtil.FORMAT_DATE) <= 0;
        if(!isEnd ||(offset < 0) ){
            time = DateUtil.getStringByOffset(time,DateUtil.FORMAT_DATE,Calendar.DAY_OF_MONTH,offset);
            tvTime.setText(time);
        }
        return  isEnd;
    }

    /**
     * 控制抽屉开关
     */
    private void drawerLayout(){
        if (!drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.openDrawer(Gravity.LEFT);
        } else {
            drawerLayout.closeDrawers();
        }
    }


    @OnClick({R.id.sel_station, R.id.iv_before, R.id.tv_time, R.id.iv_after, R.id.sel_factor})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sel_factor:
                if(factorPicker == null){
                    initFactorPicker();
                }
                factorPicker.show();
                break;
            case R.id.sel_station:
                if(drawerFrag == null){
                    // 添加抽屉Fragment
                    drawerFrag = new StationTreeFragment();
                    drawerFrag.setCurType(StationExpandAdapter.CB_SELECTE);
                    drawerFrag.setOnClickListener(onClicklistener);
                    getSupportFragmentManager().beginTransaction().replace(R.id.drawer_container, drawerFrag).commit();

                }
                drawerLayout();
                break;
            case R.id.iv_before:
                timeOffset(-1);
                getAnalyzeDatas();
                break;
            case R.id.tv_time:
                if(timePickerView == null){
                    initDatePicker();
                }
                timePickerView.show();
                break;
            case R.id.iv_after:
                if(timeOffset(1)){
                    ToastUtil.showShort(ctx,"不能超过当前日期");
                }else {
                    getAnalyzeDatas();
                }
                break;

        }
    }

    /**
     * 站点抽屉布局按钮点击监听
     */
    private StationTreeFragment.OnClickListener onClicklistener = new StationTreeFragment.OnClickListener() {
        @Override
        public void onConfirmClick(String mn) {
            if(mn != null){
                curMNs = mn;
                getAnalyzeDatas();
            }
            drawerLayout();
        }

        @Override
        public void onConfirmClick(String mn, String name) {

        }

        @Override
        public void onCancelClick() {
            drawerLayout();
        }
    };

    /**
     * 时间选择
     * @param date
     * @param v
     */
    @Override
    public void onTimeSelect(Date date, View v) {
        time = DateUtil.getStringByFormat(date,DateUtil.FORMAT_DATE);
        tvTime.setText(time);
        getAnalyzeDatas();
    }

    /**
     * 因子选择
     * @param options1
     * @param options2
     * @param options3
     * @param v
     */
    @Override
    public void onOptionsSelect(int options1, int options2, int options3, View v) {
        curTypeStr  = factorList.get(options1);
        curType = options1+1;
        selFactor.setText(curTypeStr);
        getAnalyzeDatas();
    }

}
